import {
  ITreeExpBarController,
  ITreeController,
  IMDControlController,
} from '@ibiz-template/runtime';
import { IAppDEMultiDataView } from '@ibiz/model-core';
import { PickupViewEngine } from './pickup-view.engine';

export class PickupView2Engine extends PickupViewEngine {
  /**
   * 数据缓存 （树加载完成 但是右侧的选择视图未准备好时 需缓存数据 等选择视图准备好 再执行load）
   *
   * @author zk
   * @date 2023-08-04 06:08:30
   * @type {IData[]}
   * @memberof PickupView2Engine
   */
  protected dataCache!: IData[];

  /**
   * 树导航栏
   *
   * @readonly
   * @memberof TreeExpViewEngine
   */
  get treeExpBar(): ITreeExpBarController {
    return this.view.getController('treeexpbar') as ITreeExpBarController;
  }

  /**
   * 树导航栏
   *
   * @readonly
   * @memberof TreeExpViewEngine
   */
  get tree(): ITreeController {
    return this.treeExpBar.xDataController as ITreeController;
  }

  /**
   * 选择视图多数据控制器
   *
   * @author zk
   * @date 2023-08-04 06:08:48
   * @readonly
   * @type {(IMDControlController | undefined)}
   * @memberof PickupView2Engine
   */
  get pickUpViewXDataController(): IMDControlController | undefined {
    const xDataName = (
      this.pickupViewPanel.embedView?.model as IAppDEMultiDataView
    )?.xdataControlName;
    if (!xDataName) {
      return;
    }
    return this.pickupViewPanel.embedView.getController(
      xDataName,
    ) as IMDControlController;
  }

  /**
   * 视图created生命周期执行逻辑
   *
   * @return {*}  {Promise<void>}
   * @memberof PickupView2Engine
   */
  async onCreated(): Promise<void> {
    await super.onCreated();
    const { childNames } = this.view;
    childNames.push('treeexpbar');
    if (!this.view.slotProps.pickupviewpanel) {
      this.view.slotProps.pickupviewpanel = {};
    }
    this.view.slotProps.pickupviewpanel.noLoadDefault = true;
  }

  /**
   * 视图mounted生命周期执行逻辑
   *
   * @return {*}  {Promise<void>}
   * @memberof PickupView2Engine
   */
  async onMounted(): Promise<void> {
    await super.onMounted();
    this.pickupViewPanel.state.singleSelect = true;
    this.treeExpBar.load();
    this.tree.evt.on('onActive', event => {
      this.xDataActive(event.data);
    });
    this.pickupViewPanel.evt.on('onPickUpViewMounted', () => {
      this.xDataActive(
        this.dataCache ? this.dataCache : [this.tree.state.items[0]],
      );
    });
  }

  /**
   * 树数据激活
   *
   * @author zk
   * @date 2023-08-04 02:08:23
   * @protected
   * @param {IData} data
   * @memberof PickupView2Engine
   */
  protected async xDataActive(data: IData[]): Promise<void> {
    if (!this.pickUpViewXDataController) {
      this.dataCache = data;
      return;
    }
    const viewMsg = this.treeExpBar.getNavViewMsg(
      data,
      this.view.context,
      this.view.params,
    );
    if (!viewMsg) {
      return;
    }
    const { context, params } = viewMsg;
    // 处理参数
    this.pickupViewPanel.embedView.call('load', { context, params });
  }
}
